from datetime import datetime
import sys

from api.dataapi.task_institution_ranking import institution_task_top_by_month, institution_task_top_ranking_v2

sys.path.append("../")  # noqa
from bson import ObjectId

from api.dataapi.task import task_activity_contacts, task_activity_institution, task_alumni_join_act, \
    task_alumni_belongs_permission
from api.dataapi.task_ranking import task_top_by_month, task_top_ranking_v2
from clis.check_orphan import check_orphan
from clis.top11 import yield_month
from config import col_okr, col_register
from task_utils.task_alumni_completion import task_update_alumni_completion_score
from worker_celery import celery_app


@celery_app.task(max_retry=3)
def job_update_ranking():
    year = datetime.utcnow().year
    okr = col_okr.find({"year": year}).distinct("dept_id")
    for dept in okr:
        for range_param in yield_month(year, 1, 12):
            task_top_by_month(inst_id=dept, **range_param)
            institution_task_top_by_month(inst_id=dept, **range_param)



@celery_app.task(max_retry=3, soft_time_limit=30)
def job_join_act_contacts(update_act_ids):
    """更新活动的报名人次"""
    for act_id in update_act_ids:
        task_activity_contacts(act_id)


@celery_app.task(max_retry=5, soft_time_limit=30)
def job_update_alumni_completion_score(update_person_ids):
    """计算人才得分完整度"""

    if isinstance(update_person_ids, str):
        update_person_ids = [update_person_ids]

    for person in update_person_ids:
        task_update_alumni_completion_score(person)

    # 计算分 更新排行榜
    job_update_ranking()
    job_update_ranking_v2()


@celery_app.task()
def job_institution_to_act(update_act_ids):
    """把部门信息写入活动表"""
    for act_id in update_act_ids:
        task_activity_institution(str(act_id))


@celery_app.task(default_retry_delay=300, max_retry=5, soft_time_limit=30)
def job_alumni_join_act(update_person_ids):
    """计算人报名人次 task_alumni_join_act"""

    for person_id in update_person_ids:
        task_alumni_join_act(str(person_id))


@celery_app.task()
def job_alumni_belong_dept(act_id: str):
    """更新人的部门权限"""
    act_id = ObjectId(act_id)
    update_person_ids = col_register.find({"activity_id": act_id}).distinct("person_id")
    for person_id in update_person_ids:
        task_alumni_belongs_permission(str(person_id))


@celery_app.task(default_retry_delay=300, max_retry=5, soft_time_limit=120)
def job_check_orphan():
    """移除无效的报名refs_person_ids"""
    print('定时任务...')
    check_orphan()


@celery_app.task(default_retry_delay=300, max_retry=5, soft_time_limit=120)
def job_update_ranking_v2():
    """移除无效的报名refs_person_ids"""
    okr = col_okr.find({})
    for o in okr:
        dept = o.get("dept_id")
        task_top_ranking_v2(dept)
        institution_task_top_ranking_v2(dept)


if __name__ == '__main__':
    job_alumni_belong_dept("63492715a94e13a8f3dc5a50")
